import { Table, Divider, Button, Row, Rate, Empty, message } from 'antd';
import { UploadOutlined } from '@ant-design/icons';
import React, { ReactNode, useState, useEffect, createContext } from 'react';
import { sheachHeader, defaultCustomizeTable } from './configure';
import SearchHeader from './SearchHeader';
import './styles/index.less';
import { convertData, exportJsonToExcel } from './exportFile';
import { exportRecordList, getRecordList } from '@/api';
import { filterRecordList } from '@/utils';
import FileSaver from 'file-saver';
import dayjs from 'dayjs';
import useSyncState from '@/hooks/useSyncState';
import { Modal } from 'antd';
import styled from '@emotion/styled';
import ResizeTable from './ResizeTable';
import { useTranslation } from 'react-i18next';

const PhoneText = styled.p`
	margin: 20px 0;
	font-weight: 700;
	text-align: left;
	font-size: 20px;
`;

const CustomizeRecordTable = (props: { active: boolean }) => {
	const { t } = useTranslation();
	const [recordList, setRecordList] = useState<any[]>([]);
	const [loading, setLoading] = useState<boolean>(true);
	const [searchParams, setSearchParams] = useSyncState<{
		sn: string;
		orderId: string;
		sessionStartAt: any;
		sessionEndAt: any;
		agentName: string;
		isAccepted: any;
		score: any;
		page: number;
		pageSize: number;
		total: number;
	}>({ sn: '', orderId: '', sessionStartAt: '', sessionEndAt: '', agentName: '', isAccepted: '', score: '', page: 1, pageSize: 10, total: 0 });

	useEffect(() => {
		fetchRecordList(null);
	}, [props]);

	const fetchRecordList = async (params: any) => {
		setLoading(true);
		try {
			const { data } = await getRecordList(params);
			if (data.code === '0000') {
				const respone: any[] = filterRecordList(data.data.data || []);
				setRecordList(respone);
				setSearchParams({ ...searchParams(), total: data.data.count || 0 });
			}
		} catch (error) {
			console.log(error);
		} finally {
			setLoading(false);
		}
	};

	const submitSearch = (params: any) => {
		const query = {
			sn: params.sn || '',
			orderId: params.orderId || '',
			phone: params.phone || '',
			sessionStartAt: params.date && params.date.length > 0 ? dayjs(params.date[0]._d).toISOString() : '',
			sessionEndAt: params.date && params.date.length > 1 ? dayjs(params.date[1]._d).toISOString() : '',
			agentName: params.agentName || '',
			isAccepted: params.isAccepted === 'no' ? 'false' : params.isAccepted === 'yes' ? true : '',
			score: params.score || ''
		};
		setSearchParams({ ...searchParams(), ...query });
		fetchRecordList({ ...searchParams(), total: '' });
	};

	const filterRecordData = () => {
		const _data: any[] = recordList;
		_data.forEach((item, index) => {
			item.index = index + 1;
		});
		return _data;
	};

	const showPhone = (value: string) => {
		const copyToClipboard = (text: string) => {
			const textArea = document.createElement('textarea');
			textArea.value = text;
			document.body.appendChild(textArea);
			textArea.select();
			try {
				const successful = document.execCommand('copy');
				const msg = successful ? 'successful' : 'unsuccessful';
				console.log('Copying text command was ' + msg);
			} catch (err) {
				console.log('Oops, unable to copy');
			}
			document.body.removeChild(textArea);
		};

		Modal.info({
			className: 'phone-confirm',
			title: t('user-information-mobile'),
			closable: true,
			okText: t('confirm'),
			content: (
				<div>
					<PhoneText>{value}</PhoneText>
				</div>
			),

			onOk() {
				// copyToClipboard(value);
			}
		});
	};

	const customizeColums = () => {
		defaultCustomizeTable.forEach((column: { title: string; i18nKey: string; dataIndex: string; key: string; render?: (props: any) => ReactNode }, index) => {
			if (column.key === 'isAccepted') {
				column.render = value => <span>{value === 'yes' ? t('yes') : t('no')}</span>;
			}
			if (column.key === 'phone') {
				column.render = value => <span onClick={() => showPhone(value)}>{typeof value === 'string' ? value.replace(value.substr(3, 4), '****') : '--'}</span>;
			}
			column.title = t(`${column.i18nKey}`);
		});
		console.log(defaultCustomizeTable);

		return defaultCustomizeTable;
	};

	const changePageSize = (page: number, pageSize: number) => {
		setSearchParams({ ...searchParams(), page, pageSize });
		fetchRecordList({ ...searchParams(), total: '' });
	};

	const exportFile = async () => {
		let headerMap = {
			index: '序号',
			openId: '微信OpenID',
			sn: '序列号',
			device: '机型',
			userName: '客户名',
			company: '所属公司',
			mobile: '手机号',
			callTime: '发起呼叫时间',
			waitTime: '等待时间',
			startTime: '通话开始时间',
			endTime: '通话结束时间',
			totalTime: '通话总计时长',
			orderId: '工单号',
			status: '工单状态',
			serviceNo: '客服工号',
			isAccepted: '是否接通',
			score: '评价',
			suggestion: '评价留言'
		};
		console.log(filterRecordData());

		// let tableData = filterRecordData().map((column, idx) => ({
		// 	index: idx + 1,
		// 	openId: column.openId,
		// 	sn: column.sn,
		// 	device: column.PROD_MODEL,
		// 	userName: column.ZLXR_NAME,
		// 	company: column.ZKH_NAME,
		// 	mobile: column.phone,
		// 	callTime: column.createdAt,
		// 	waitTime: column.waitTime,
		// 	startTime: column.sessionStartAt,
		// 	endTime: column.sessionEndAt,
		// 	totalTime: column.totalTime,
		// 	businessNo: column.orderId,
		// 	status: column.ZACT_TEXT,
		// 	serviceNo: column.ZTS_ID,
		// 	isAccepted: column.isAccepted === 'yes' ? '是' : '否',
		// 	score: column.score,
		// 	suggestion: column.suggestion
		// }));
		// let obj = convertData(tableData, headerMap);
		// exportJsonToExcel({
		// 	header: obj.header,
		// 	data: obj.data,
		// 	filename: `${new Date().getTime()}-坐席记录数据`,
		// 	autoWidth: true,
		// 	bookType: 'xlsx'
		// });
		try {
			const data = await exportRecordList();
			if (data.data) {
				const xlsx = new Blob([data.data]);
				// let downloadElement = document.createElement('a');
				// let href = window.URL.createObjectURL(xlsx);
				// downloadElement.href = href;
				// downloadElement.download = '反馈消息表.xlsx';　　　　　　　　　　// xxx.xls/xxx.xlsx
				// document.body.appendChild(downloadElement);
				// downloadElement.click();
				// document.body.removeChild(downloadElement);
				// window.URL.revokeObjectURL(href);
				FileSaver.saveAs(xlsx, `${new Date().getFullYear() + '年' + (new Date().getMonth() + 1) + '月' + new Date().getDate() + '日'}` + '.xlsx');
				message.warning(t('downloaded-service-record-successfully') + '!');
			}
		} catch (error) {
			message.warning(t('downloaded-service-record-failed') + '!');
		}
	};

	return (
		<div className="widget-customize-table-wrapper">
			<Row className="search-wrapper">
				<SearchHeader searchParams={sheachHeader} submitSearch={submitSearch} />
			</Row>
			<Divider />
			<Row className="export-btn">
				<Button type="primary" icon={<UploadOutlined />} disabled={filterRecordData().length === 0} onClick={exportFile}>
					{t('export')}
				</Button>
			</Row>
			<Row className="table-wrapper">
				{/* <Table scroll={{ x: 0, y: window.innerHeight - 400 }} tableLayout={'fixed'} loading={loading} dataSource={filterRecordData()} columns={customizeColums()} rowKey={'index'} pagination={{ position: ['bottomCenter'], onChange: changePageSize, current: searchParams().page, pageSize: searchParams().pageSize, total: searchParams().total }} /> */}
				{/* <ResizeTable dataSource={filterRecordData()} loading={loading} cols={customizeColums()} columns={customizeColums()} pagination={{ position: ['bottomCenter'], onChange: changePageSize, current: searchParams().page, pageSize: searchParams().pageSize, total: searchParams().total }}></ResizeTable> */}
				<ResizeTable
					dataSource={filterRecordData()}
					loading={loading}
					columns={customizeColums()}
					pagination={{ position: ['bottomCenter'], onChange: changePageSize, current: searchParams().page, pageSize: searchParams().pageSize, total: searchParams().total }}
				></ResizeTable>
			</Row>
		</div>
	);
};

export default CustomizeRecordTable;
